<template>
  <view class="container">
    <view
      v-for="(order, index) in orders"
      :key="order.id"
      class="order-card "
    >
      <view class="order-info" @click="goToDetail(order.faultId)">
        <text>{{ order.addressstring }}</text>
		<view class="distance-row">
		  <text v-if="order.distance < 1000">
		    距您约 {{ order.distance }} m
		  </text>
		  <text v-else>
		    {{ (order.distance / 1000).toFixed(2) }} km
		  </text>
		  <uni-icons
		    type="location"
		    size="16"
		    color="#007aff"
		    class="nav-icon"
		    @click="fetchStationCoordinates(order.latitude, order.longitude)"
		  />
		</view>
		<text>故障原因：{{ order.description }}</text>
		<text>本单金额：{{ order.price }}</text>
        <text>
          截止时间：{{
            parseTime(
              order.dispatchType === 2
                ? order.stepOneTime
                : order.dispatchType === 3
                ? order.stepTwoTime
                : ''
            )
          }}
        </text>
      </view>
      <button
        class="rob-btn"
        :disabled="order.robbed"
        @click="robOrder(order.id, index)"
      >
        {{ order.robbed ? '接' : '抢' }}
      </button>
    </view>
	<!-- 无订单提示 -->
	<view v-if="orders.length === 0 && !loadingMore" class="no-orders">
	  当前无单可抢，请稍后
	</view>

    <!-- 加载更多提示 -->
    <view class="load-more" v-if="loadingMore">
      加载中...
    </view>
	<view class="refresh-btn" @click="getLocationAndLoadOrders">
	  <uni-icons type="refresh" size="24" color="#fff" />
	</view>
  </view>

</template>

<script>
import * as faultApi from '@/api/oper/fault/fault.js';
import {parseTime,getDistanceInMeters,fetchStationCoordinates} from '@/utils/ruoyi.js';


export default {
  data() {
    return {
      orders: [],
      latitude: 0,
      longitude: 0,
      pageNo: 1,
      pageSize: 10,
      loadingMore: false,
      finished: false
    };
  },
  onLoad() {
    this.getLocationAndLoadOrders(true);
  },
  // 下拉刷新（页面生命周期）
  onPullDownRefresh() {
    this.pageNo = 1;
    this.finished = false;
    this.getLocationAndLoadOrders(true);
  },
  // 上滑加载更多
  onReachBottom() {
    if (!this.finished) {
      this.pageNo++;
      this.getLocationAndLoadOrders(false);
    }
  },
  methods: {
	  parseTime,
	  getDistanceInMeters,
	  fetchStationCoordinates,
    getLocationAndLoadOrders(isRefresh = false) {
      uni.getLocation({
        type: 'gcj02',
		isHighAccuracy:true,
		highAccuracyExpireTime:4000,
        success: (res) => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          this.loadOrders(isRefresh);
        },
        fail: () => {
          uni.showToast({ title: '定位失败', icon: 'none' });
          this.loadOrders(isRefresh);
        }
      });
    },

    async loadOrders(isRefresh = false) {
      if (!isRefresh) this.loadingMore = true;

      const res = await faultApi.getOrderList({
        pageNo: this.pageNo,
        pageSize: this.pageSize
      });

      const list = res.data.list || [];
      const ordersWithDistance = list.map(order => {
        let distance = 0;
        if (order.latitude && order.longitude && this.latitude && this.longitude) {
          distance = getDistanceInMeters(this.latitude, this.longitude, order.latitude, order.longitude);
        }
        return {
          ...order,
          distance,
          robbed: false
        };
      });

      if (isRefresh) {
        this.orders = ordersWithDistance;
        uni.stopPullDownRefresh();
      } else {
        this.orders = [...this.orders, ...ordersWithDistance];
      }

      this.loadingMore = false;
      if (ordersWithDistance.length < this.pageSize) {
        this.finished = true;
      }
    },

    async robOrder(orderId, index) {
      const res = await faultApi.robOrder(orderId);
      if (res.code === 0) {
        uni.showToast({ title: '抢单成功', icon: 'success' });
        this.orders[index].robbed = true;
		setTimeout(() => {
		  this.getLocationAndLoadOrders(true);
		}, 5000);		
      } else {
        uni.showToast({ title: res.message || '抢单失败', icon: 'none' });
      }
    },
	goToDetail(orderId) {
	  uni.navigateTo({ url: `/pages/order/detail?orderId=${orderId}` });
	},
  }
};
</script>

<style scoped>

.container {
  padding: 20rpx;
}
.order-card {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.order-info {
  flex: 1;
}
.order-info text {
  display: block;
  margin-bottom: 10rpx;
}
.rob-btn {
  background-color: #ff5500;
  color: #fff;
  font-size: 36rpx;
  border-radius: 50%;
  width: 100rpx;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  position: relative;
  flex-shrink: 0;
}
.rob-btn[disabled] {
  background-color: #ccc;
}
.load-more {
  text-align: center;
  color: #999;
  font-size: 26rpx;
  padding: 20rpx 0;
}
.distance-row {
  display: inline-flex;
  align-items: center;
  flex-wrap: nowrap;
}
.no-orders {
  text-align: center;
  font-size: 28rpx;
  color: #999;
  margin-top: 100rpx;
}

.nav-icon {
  margin-left: 10rpx;
  font-size: 24rpx;
  color: #007aff;
  line-height: 1;
}
.refresh-btn {
  position: fixed;
  bottom: 120rpx;
  right: 80%;
  width: 100rpx;
  height: 100rpx;
  background-color: #007aff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
  z-index: 999;
}
</style>
